package dialogs.ranking;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JPanel;

import persistence.Game;
import persistence.Player;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

import dialogs.ChildController;

public class RankingController extends ChildController implements ActionListener{
	
	private RankingView view;
	private RankingTableModel tableModel;
	
	private ObjectContainer db;
	
	public RankingController(ObjectContainer db) {
		this.db = db;
		tableModel = new RankingTableModel();	
		ArrayList<Player> players = new ArrayList<Player>();
        ObjectSet<Player> presult = db.queryByExample( Player.class );
		for (Player p : presult){
			players.add( p );
		}
		ArrayList<Game> games = new ArrayList<Game>();
        ObjectSet<Game> gresult = db.queryByExample( Game.class );
		for (Game g : gresult){
			games.add( g );
		}
		// Liste von Spielern und Liste von Spielen setzen setzen
		tableModel.setPlayers(players);
		tableModel.setGames(games);
		
		view = new RankingView(tableModel);
	}
	public RankingTableModel getTableModel() {
		return tableModel;
	}
	@Override
	public void updateFromDatabase() {

		ObjectSet<Game> result = db.queryByExample(Game.class);

		for (Game game1 : result) {
			if (!tableModel.containsGame(game1)) {
				// Game zu Model hinzufuegen, falls es noch nicht vorhanden
				// ist
				tableModel.addGame(game1);
			}
		}
		ObjectSet<Player> playerResult = db.queryByExample(Player.class);
		
		for (Player player : playerResult) {	
			if(! tableModel.containsPlayer(player)) {
				// Spieler zu Model hinzufuegen, falls er noch nicht vorhanden
				// ist
				tableModel.addPlayer(player);
			}
		}
	}

	@Override
	public JPanel getView() {
		return view;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}
